package tools.texture.view {
	import flash.display.DisplayObject;

	import tools.model.FrameInfo;

	import kiwi.util.GeomUtils;

	import tools.model.TextureBitmap;
	import tools.model.TileInfo;

	import org.aswing.ASColor;
	import org.aswing.Container;
	import org.aswing.SolidBackground;

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.geom.Point;

	/**
	 * 图片预览容器
	 * @author zhangming.luo
	 */
	public class PreviewContainer extends Container {
		private var canvas : Bitmap;
		private var _registration : Point;
		private var container : Sprite;
		private var coordinate : Shape;
		private var _dos : DisplayObject;

		public function PreviewContainer() {
			setBackgroundDecorator(new SolidBackground(new ASColor(0xff00ff, 0.3)));
			container = new Sprite();
			coordinate = new Shape();
			coordinate.graphics.lineStyle(1, 0x000000, 0.3);
			coordinate.graphics.moveTo(-1024, 0);
			coordinate.graphics.lineTo(1024, 0);
			coordinate.graphics.moveTo(0, -1024);
			coordinate.graphics.lineTo(0, 1024);
			container.addChild(coordinate);
			canvas = new Bitmap();
			container.addChild(canvas);
			addChild(container);
		}

		public function setTile(tile : TileInfo) : void {
			var bd : BitmapData = new BitmapData(tile.source.width, tile.source.height, true, 0x0);
			bd.copyPixels(tile.$source.bitmapData, tile.source, GeomUtils.ZERO);
			setBitmap(bd);
			setRegistration(tile.registration);
		}

		public function setFrame(frame : FrameInfo) : void {
			if (frame) {
				setBitmap(frame.getBitmapData());
				setRegistration(frame.$registration);
			} else {
				canvas.bitmapData = null;
			}
		}

		public function setDisplayObject(dos : DisplayObject) : void {
			setBitmap(null);
			if (_dos) {
				container.removeChild(_dos);
			}
			_dos = dos;
			container.addChild(_dos);
			setRegistration(null);
		}

		public function setTexture(texture : TextureBitmap) : void {
			setBitmap(texture.bitmapData);
			setRegistration(null);
		}

		private function setBitmap(bd : BitmapData) : void {
			canvas.bitmapData = bd;
		}

		private function setRegistration(registration : Point) : void {
			_registration = registration || GeomUtils.ZERO;
			updateUI();
		}

		override public function updateUI() : void {
			super.updateUI();
			container.x = width / 2;
			container.y = height / 2;
			canvas.x = -_registration.x;
			canvas.y = -_registration.y;
		}
	}
}
